﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using WPFServices.Commands;
using WPFServices.Models.Domain;
using WPFServices.Services.DomainService.BomInfo;
using WPFServices.Services.DomainService.Role;
using WPFServices.Views.DomainViews.Material;
using WPFServices.Views.DomainViews.ProcessRouteinfo;
using WPFServices.Views.DomainViews.Productinfo;
using WPFServices.ViewModels.DomainViewModel.Productinfo;

namespace WPFServices.ViewModels.DomainViewModel.BomInfo
{
    public class AddBomViewModel : BaseViewModel
    {
        private readonly BomService _bomService;
        private string _bomCode;
        private bool _defaultBom;
        private string _bomVersion;
        private int _productId;
        private int _processRouteId;
        private string _dailyOutput;
        private int _bomParentId;
        private ProductDto _selectedProduct;
        private ProcessRouteDto _selectedProcessRoute;
        private BomDto _selectedParentBom;
        private ObservableCollection<MaterialItem> _materials;

        public AddBomViewModel()
        {
            _bomService = new BomService();
            _materials = new ObservableCollection<MaterialItem>();
            
            // 生成默认BOM编号
            BomCode = $"BOM{DateTime.Now:yyyyMMddHHmmss}";
            
            // 初始化默认值
            DefaultBom = false; // 默认不勾选
            BomParentId = 0; // 默认为0
            
            SaveCommand = new RelayCommand(async _ => await SaveBomAsync(), _ => CanSave());
            CancelCommand = new RelayCommand(_ => Cancel());
            SelectProductCommand = new RelayCommand(_ => SelectProduct());
            AddMaterialCommand = new RelayCommand(_ => AddMaterial());
            RemoveMaterialCommand = new RelayCommand(_ => RemoveMaterial());
            AddProcessRouteCommand = new RelayCommand(_ => AddProcessRoute());
            SelectParentBomCommand = new RelayCommand(_ => SelectParentBom());
        }

        public event Action<bool> CloseWindow;

        #region 属性
        public string BomCode
        {
            get => _bomCode;
            set => SetProperty(ref _bomCode, value);
        }

        public bool DefaultBom
        {
            get => _defaultBom;
            set => SetProperty(ref _defaultBom, value);
        }

        public string BomVersion
        {
            get => _bomVersion;
            set => SetProperty(ref _bomVersion, value);
        }

        public int ProductId
        {
            get => _productId;
            set => SetProperty(ref _productId, value);
        }

        public int ProcessRouteId
        {
            get => _processRouteId;
            set => SetProperty(ref _processRouteId, value);
        }

        public string DailyOutput
        {
            get => _dailyOutput;
            set => SetProperty(ref _dailyOutput, value);
        }

        public int BomParentId
        {
            get => _bomParentId;
            set => SetProperty(ref _bomParentId, value);
        }

        public ProductDto SelectedProduct
        {
            get => _selectedProduct;
            set
            {
                if (SetProperty(ref _selectedProduct, value))
                {
                    // 自动同步ProductId
                    ProductId = value?.Id ?? 0;
                }
            }
        }

        public ObservableCollection<MaterialItem> Materials
        {
            get => _materials;
            set => SetProperty(ref _materials, value);
        }

        public ProcessRouteDto SelectedProcessRoute
        {
            get => _selectedProcessRoute;
            set
            {
                if (SetProperty(ref _selectedProcessRoute, value))
                {
                    // 自动同步ProcessRouteId
                    ProcessRouteId = value?.Id ?? 0;
                }
            }
        }

        public BomDto SelectedParentBom
        {
            get => _selectedParentBom;
            set
            {
                if (SetProperty(ref _selectedParentBom, value))
                {
                    // 自动同步BomParentId
                    BomParentId = value?.Id ?? 0;
                }
            }
        }
        #endregion

        #region 命令
        public RelayCommand SaveCommand { get; }
        public RelayCommand CancelCommand { get; }
        public RelayCommand SelectProductCommand { get; }
        public RelayCommand AddMaterialCommand { get; }
        public RelayCommand RemoveMaterialCommand { get; }
        public RelayCommand AddProcessRouteCommand { get; }
        public RelayCommand SelectParentBomCommand { get; }
        public Action<ProductDto> OnProductSelected { get; set; }
        #endregion

        #region 方法
        private bool CanSave()
        {
            // 检查必填字段：BOM版本和产品
            return !string.IsNullOrWhiteSpace(BomVersion) && SelectedProduct != null;
        }

        private async Task SaveBomAsync()
        {
            try
            {
                // 验证必填字段
                if (string.IsNullOrWhiteSpace(BomVersion))
                {
                    MessageBox.Show("请输入BOM版本", "验证失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                if (SelectedProduct == null)
                {
                    MessageBox.Show("请选择产品", "验证失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // 使用用户输入的BOM编号，如果没有输入则生成一个
                var bomCodeToUse = string.IsNullOrWhiteSpace(BomCode) || BomCode == "系统自动生成" 
                    ? $"BOM{DateTime.Now:yyyyMMddHHmmss}" 
                    : BomCode.Trim();
                
                var createDto = new CreateorUpdateBomDto
                {
                    BomCode = bomCodeToUse, // 使用用户输入或生成的BOM编号
                    DefaultBom = DefaultBom, // 根据复选框状态设置
                    BomVersion = BomVersion?.Trim(), // 手动填写的版本
                    ProductId = ProductId, // 选择产品后获取的ID
                    ProcessRouteId = ProcessRouteId, // 选择工艺路线后获取的ID
                    DailyOutput = DailyOutput?.Trim(), // 手动填写的日产量
                    BomParentId = BomParentId // 默认为0
                };


                
                // 验证关键字段
                if (createDto.ProductId <= 0)
                {
                    MessageBox.Show("产品ID无效，请重新选择产品", "验证失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                
                if (string.IsNullOrWhiteSpace(createDto.BomVersion))
                {
                    MessageBox.Show("BOM版本不能为空", "验证失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // 调用BomService的CreateBomAsync方法
                var result = await _bomService.CreateBomAsync(createDto);

                // 显示成功消息
                MessageBox.Show("新增BOM成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                
                // 关闭窗口并返回成功状态
                CloseWindow?.Invoke(true);
            }
            catch (Exception ex)
            {
                // 显示错误消息
                MessageBox.Show($"新增BOM失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                
                // 不关闭窗口，让用户继续编辑
            }
        }

        private void Cancel()
        {
            CloseWindow?.Invoke(false); // 返回false表示取消
        }

        private void AddMaterial()
        {
            var materialSelectionWindow = new WPFServices.Views.DomainViews.Material.MaterialSelectionWindow();
            if (materialSelectionWindow.ShowDialog() == true && materialSelectionWindow.SelectedItem != null)
            {
                var selectedItem = materialSelectionWindow.SelectedItem;
                
                if (selectedItem is MaterialDto material)
                {
                    var materialItem = new MaterialItem
                    {
                        Index = Materials.Count + 1,
                        Name = material.MaterialName,
                        Code = material.MaterialCode,
                        Specification = material.Specification,
                        Unit = material.UnitName
                    };
                    Materials.Add(materialItem);
                }
                else if (selectedItem is ProductDto product)
                {
                    var materialItem = new MaterialItem
                    {
                        Index = Materials.Count + 1,
                        Name = product.ProductName,
                        Code = product.ProductCode,
                        Specification = product.Specification,
                        Unit = product.UnitName
                    };
                    Materials.Add(materialItem);
                }
            }
        }

        private void RemoveMaterial(object parameter = null)
        {
            if (parameter is MaterialItem materialToRemove)
            {
                // 删除指定的物料
                Materials.Remove(materialToRemove);
            }
            else if (Materials.Count > 0)
            {
                // 如果没有指定参数，删除最后一个
                Materials.RemoveAt(Materials.Count - 1);
            }
            
            // 重新编号
            for (int i = 0; i < Materials.Count; i++)
            {
                Materials[i].Index = i + 1;
            }
        }

        private void SelectProduct()
        {
            try
            {
                var productWindow = new ProductViewWindow();
                productWindow.Owner = System.Windows.Application.Current.MainWindow;

                if (productWindow.ShowDialog() == true)
                {
                    var productViewModel = productWindow.DataContext as ProductViewModel;
                    if (productViewModel?.SelectedProduct != null)
                    {
                        SelectedProduct = productViewModel.SelectedProduct;
                        ProductId = productViewModel.SelectedProduct.Id;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"选择产品失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void AddProcessRoute()
        {
            var processRouteSelectionWindow = new WPFServices.Views.DomainViews.ProcessRouteinfo.ProcessRouteSelectionWindow();
            if (processRouteSelectionWindow.ShowDialog() == true && processRouteSelectionWindow.SelectedProcessRoute != null)
            {
                SelectedProcessRoute = processRouteSelectionWindow.SelectedProcessRoute;
            }
        }

        private void SelectParentBom()
        {
            try
            {
                var bomSelectionWindow = new WPFServices.Views.DomainViews.BomInfo.BomSelectionWindow();
                bomSelectionWindow.Owner = System.Windows.Application.Current.MainWindow;

                if (bomSelectionWindow.ShowDialog() == true && bomSelectionWindow.SelectedBom != null)
                {
                    SelectedParentBom = bomSelectionWindow.SelectedBom;
                    BomParentId = bomSelectionWindow.SelectedBom.Id;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"选择上级BOM失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        #endregion
    }

    // 物料项类
    public class MaterialItem
    {
        public int Index { get; set; }
        public string Name { get; set; }
        public string Code { get; set; }
        public string Specification { get; set; }
        public string Unit { get; set; }
    }
}